<template>
  <div class="inner-container">
    <div class="left-container">
      <!-- 分页 -->
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="90px"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="紧急程度" prop="urgent">
              <el-radio-group v-model="temp.urgent" :disabled="flowStatus > 1">
                <el-radio :label="0">正常</el-radio>
                <el-radio :label="1">紧急</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="文件编号" min-width="220">
              <el-input
                v-model.trim="temp.documentCode"
                :disabled="flowStatus > 1"
                @input="search"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="文件名称">
              <el-input v-model="temp.documentName" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="版本号">
              <el-select
                v-model="v1"
                disabled
                size="small"
                placeholder="A"
                style="width: 60px"
                @change="handleVChange"
              >
                <el-option
                  v-for="item in v1Options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-input-number
                v-model="v2"
                :disabled="flowStatus > 1"
                size="small"
                :min="0"
                :max="9"
                controls-position="right"
                style="width: 75px"
                @change="handleVChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="申请原因" prop="reason">
              <el-input
                v-model.trim="temp.reason"
                :disabled="flowStatus > 1"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item v-if="flowStatus == 4" label="借阅文件">
              <el-tag>{{ temp.documentName }}</el-tag>
            </el-form-item>
            <el-form-item v-if="flowStatus == 1" label="审核人" prop="reviewer">
              <el-tag
                v-for="(tag, index) in temp.reviewName"
                :key="index"
                :disable-transitions="false"
                class="tag"
              >
                {{ tag.userName }}
              </el-tag>
              <el-button
                size="mini"
                round
                circle
                icon="el-icon-plus"
                @click="openReview(0, 'qa', 'QA')"
              />
            </el-form-item>
            <el-form-item
              v-if="flowStatus == 2 && temp.result != 2"
              label="审批人"
              prop="reviewer"
            >
              <el-tag
                v-if="temp.reviewName"
                :disable-transitions="false"
                class="tag"
              >
                {{ temp.reviewName }}
              </el-tag>
            </el-form-item>
            <el-form-item
              v-if="flowStatus == 3 && temp.result != 2"
              label="处理人"
              prop="reviewer"
            >
              <el-tag
                v-if="temp.reviewName"
                :disable-transitions="false"
                class="tag"
              >
                {{ temp.reviewName }}
              </el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              v-if="flowStatus > 1"
              label="处理意见"
              prop="reviewer"
            >
              <el-input v-model.trim="temp.opinion" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              v-if="flowStatus == 2 || flowStatus == 3"
              label="处理结果"
            >
              <el-radio v-model="temp.result" :label="1">通过</el-radio>
              <el-radio
                v-model="temp.result"
                :label="2"
                @change="reject"
              >拒绝</el-radio>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item v-if="flowStatus == 4" label="借阅部门" prop="name">
              <el-tag
                v-for="(tag, index) in receiveUserGroupList"
                :key="index"
                closable
                :disable-transitions="false"
                style="margin-right: 10px"
                @close="handleCloseTagGroup(tag)"
              >
                {{ tag.label }}
              </el-tag>
              <el-tooltip effect="dark" content="选择部门" placement="top">
                <el-button
                  size="mini"
                  round
                  circle
                  icon="el-icon-plus"
                  @click="openReview(5)"
                />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="flowStatus == 4" label="借阅人员" prop="name">
              <el-tag
                v-for="(tag, index) in temp.reviewName"
                :key="index"
                closable
                :disable-transitions="false"
                style="margin-right: 10px"
                @close="handleCloseTag(tag)"
              >
                {{ tag.userName }}
              </el-tag>
              <el-tooltip effect="dark" content="选择人员" placement="top">
                <el-button
                  size="mini"
                  round
                  circle
                  icon="el-icon-plus"
                  @click="openReview(4)"
                />
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="flowStatus == 4" label="借阅日期" prop="name">
          <el-date-picker
            v-model="temp.effectDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-row style="margin-bottom: 15px">
          <el-col :span="24">
            <el-button-group>
              <el-button
                size="small"
                type="primary"
                icon="el-icon-top button-icon"
                @click="handleSubmit"
              >提交</el-button>
              <el-button
                size="small"
                icon="el-icon-close button-icon"
                @click="handleClose"
              >取消</el-button>
            </el-button-group>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="right-container">
      <el-timeline>
        <el-timeline-item
          v-for="(activity, index) in activities"
          :key="index"
          :timestamp="activity.time"
          :color="activity.color"
          placement="top"
        >
          <!-- content是显示数据 -->
          <el-tooltip effect="dark" placement="left">
            <div slot="content">
              处理人:{{ activity.handleUserName }}
              <!-- <br />第二行信息 -->
            </div>

            <p>
              <el-tag v-if="activity.handleUserName" size="small">{{
                activity.handleUserName
              }}</el-tag>{{ activity.content }}
            </p>
          </el-tooltip>
        </el-timeline-item>
      </el-timeline>
    </div>
    <SearchPersonnelType
      :search-personnel-type-data="SearchPersonnelTypeData"
      @dataList="dataList"
    />
    <SearchUserList
      :search-user-list-data="SearchUserListData"
      @SearchUserList="SearchUserList"
    />
    <SelectGroupList
      :select-group-list-data="SelectGroupListData"
      @UserGroupListData="UserGroupListData"
    />
  </div>
</template>

<script>
import {
  apply,
  approval,
  contentAudit,
  release
} from '@/api/xd/flow/flow_borrow'
import { listUserGroupAll } from '@/api/uc/userGroup'
import { list } from '@/api/fd/repository'
import {
  listTreeFolder,
  listTreeFolderOnlyFolder,
  getDocumentParticulars
} from '@/api/fd/folder'
import { getsearch, getBranchList } from '@/api/uc/search'
import { getA_ZArray } from '@/utils'
import {
  getDocumentFlowPrintAndDrop,
  getNodesHandle
} from '@/api/xd/documentFlow'
import { getDocumentByCode } from '@/api/fd/document'
import { nodeHandleByCode } from '@/api/xd/documentFlow.js'
import SearchPersonnelType from '@/components/SearchUserType/index.vue'
import SearchUserList from '@/components/SearchUserList/index'
import SelectGroupList from '@/components/SelectGroupList/index.vue'

export default {
  components: {
    SearchPersonnelType,
    SearchUserList,
    SelectGroupList
  },
  data() {
    const FLOW_TYPE_BORROW = 5
    const PHASE_APPLY = 1
    const PHASE_CONTENT_AUDIT = 2
    const PHASE_APPROVAL = 3
    const PHASE_RELEASE = 4
    return {
      title: '',
      flowStatus: 1,
      flowStatusOptions: [
        { value: PHASE_APPLY, label: '借阅申请', phase: 'newApply' },
        { value: PHASE_CONTENT_AUDIT, label: '文件审核', phase: 'audit' },
        { value: PHASE_APPROVAL, label: '审批', phase: 'approve' },
        { value: PHASE_RELEASE, label: '发行', phase: 'release' }
      ],
      v1: 'A',
      v1Options: [],
      v2: 0,
      v2Options: [],
      temp: {
        flowType: FLOW_TYPE_BORROW,
        documentName: null,
        urgent: 0,
        documentVersion: null,
        previousDocumentVersion: null,
        reason: null,
        documentId: null,
        documentManagerUserId: 1,
        documentManagerUserGroupId: 1,
        result: 1
      },
      rules: {
        documentCode: [
          { required: true, message: '文件编号不能为空', trigger: 'change' }
        ]
      },
      activities: [],
      userGroup: [],
      userGroupId: '',
      repository: [],
      repositoryId: '',
      options: [],
      dialogDocument: false,
      refresh: 0,
      uploadFolderTree: [],
      dialogReview: false,
      reviewData: [],
      reviewWindow: 0,
      reviewNameList: [],
      reviewUserId: [],
      headList: [],
      receiveUserGroupIdList: [],
      receiveUserGroupList: [],
      particularsdocumentName: '',
      // ///
      SearchPersonnelTypeData: {},
      SearchUserListData: {},
      SelectGroupListData: {}
    }
  },
  watch: {
    options: function() {
      ++this.refresh
    }
  },
  updated() {
    this.$emit('flowData', {
      flowStatus: this.flowStatus,
      documentCode: this.temp.documentCode
    })
  },
  mounted() {
    // this.getBranchList()
    this.v1Options = getA_ZArray()
    for (let i = 1; i < 10; i++) {
      const c = i
      this.v2Options.push({ value: c, label: c })
    }
    if (this.$route.query.phase) {
      this.flowStatus = this.$route.query.phase
    }
    if (this.$route.params.documentFlowId) {
      this.getFlowData(this.$route.params.documentFlowId)
    }
    this.setActivities()
    for (var i = 0; i < this.flowStatus - 1; i++) {
      this.activities[i].color = '#0bbd87'
    }
    this.activities[this.flowStatus - 1].color = '#2573dc'
    this.dynamicTitle()
  },
  methods: {
    // 动态title
    dynamicTitle() {
      if (this.flowStatus == 1) {
        this.title = '审核人'
      } else if (this.flowStatus == 2) {
        this.title = '审批人'
      } else if (this.flowStatus == 3) {
        this.title = '处理人'
      }
    },
    // 拒绝驳回
    reject() {
      // this.temp.reviewId=''
      // this.temp.reviewName=''
      // this.$forceUpdate()
    },
    async getFlowData(documentFlowId) {
      if (documentFlowId != 0) {
        await getDocumentFlowPrintAndDrop({
          documentFlowId: documentFlowId
        }).then((res) => {
          this.temp = res.data
          this.temp.result = 1
          this.v1 = this.temp.documentVersion[0]
          this.v2 = this.temp.documentVersion[1]
          this.temp.urgent = parseInt(this.temp.urgent)
        })
        this.getNodesHandle()
        if (this.flowStatus != 1 && this.flowStatus != 4) {
          await nodeHandleByCode({
            code: this.temp.documentCode,
            phase: this.temp.phase
          }).then((res) => {
            (this.temp.reviewName = res.data[0].handleUserName),
            (this.temp.reviewId = res.data[0].handleUserId)
            this.$forceUpdate()
          })
        }
      }
    },
    trainFlagRadio(val) {
      if (val == 0) {
        this.temp.reviewId = null
        this.temp.reviewName = null
      }
    },
    /**
     * 共两个参数，依次为：传递给 data 属性的数组中该节点所对应的对象、树目前的选中状态对象，
     * 包含 checkedNodes、checkedKeys、halfCheckedNodes、halfCheckedKeys 四个属性
     */
    // 操作借阅人员tag标签
    // 操作发放人员tag标签
    handleCloseTag(tag) {
      this.temp.reviewName.splice(this.temp.reviewName.indexOf(tag), 1)
      this.reviewUserId.splice(this.reviewUserId.indexOf(tag), 1)
      this.$forceUpdate()
    },
    // 发放部门
    handleCloseTagGroup(tag) {
      this.receiveUserGroupList.splice(
        this.receiveUserGroupList.indexOf(tag),
        1
      )
      this.receiveUserGroupIdList.splice(
        this.receiveUserGroupIdList.indexOf(tag),
        1
      )
    },
    handleCheckChange(obj, objs) {
      console.log('obj', obj, 'objs', objs)
      // 人员默认的
      if (this.reviewWindow == 0) {
        this.temp.reviewId = obj.id
        this.temp.reviewName = obj.label
      }
      // 选择多个人员的
      if (this.reviewWindow == 1) {
        this.temp.receiveUserIdList = obj.id
      }
      // 选择多个部门
      if (this.reviewWindow == 2) {
        this.temp.receiveUserGroupIdList = obj.id
      }
      console.log(this.temp)
    },
    // 部门获取
    async getBranchList() {
      this.headList = await getBranchList()
      console.log('head', this.headList)
    },
    //

    openDialog(val) {
      this.getUserGroup()
      this.dialogDocument = true
    },
    getDocument(val) {
      var arr = this.$refs['cascaderDocuemtn'].getCheckedNodes()[0].pathLabels
      var documentName = arr[arr.length - 1]
      this.temp.documentRealName = documentName
      this.temp.documentId = val[arr.length - 1]
      // console.log(this.temp)
      this.getDocumentParticulars()
    },
    getUserGroup() {
      // 获取部门
      listUserGroupAll({ type: 0 }).then((res) => {
        res.data.forEach((item) => {
          if (item.type == 1) {
            var data = {
              value: item.userGroupId,
              label: item.userGroupName
            }
            this.userGroup.push(data)
          }
          if (item.type == 2) {
            var data = {
              value: item.userGroupId,
              label: item.userGroupName
            }
            this.userGroup.push(data)
          }
        })
      })
    },
    setActivities() {
      this.flowStatusOptions.forEach((e) => {
        var data = {
          content: e.label,
          // timestamp: '2018-04-12 20:46',
          size: 'large',
          type: 'primary',
          phase: e.phase,
          icon: 'el-icon-more'
        }
        this.activities.push(data)
      })
    },
    handleFlowStatusChange(val) {
      for (let i = 1; i <= this.activities.length; i++) {
        if (val === i) {
          this.activities[this.activities.length - i].color = '#0bbd87'
        } else if (val > i) {
          this.activities[this.activities.length - i].color = '#888888'
        }
      }
    },
    handleVChange(val) {
      this.temp.documentVersion = this.v1 + this.v2
      this.temp.previousDocumentVersion = this.temp.documentVersion
    },
    handleSubmit() {
      if (this.flowStatus == 1) {
        this.temp.documentVersion = this.v2
        var data = {
          documentCode: this.temp.documentCode,
          documentName: this.temp.documentName,
          documentVersion: this.temp.documentVersion,
          nextHandleUserId: this.temp.reviewId,
          documentId: this.temp.documentId,
          reason: this.temp.reason,
          urgent: this.temp.urgent
        }
        if (!data.documentCode) {
          this.$message.warning('文档编码不可为空')
          return
        }
        if (!data.documentName) {
          this.$message.warning('文档名称不可为空')
          return
        }
        if (!data.reason) {
          this.$message.warning('申请原因不可为空')
          return
        }
        if (!data.nextHandleUserId) {
          this.$message.warning('审核人不可为空')
          return
        }
        if (!data.documentVersion) {
          this.$message.warning('版本不可为空')
          return
        }
        if (!data.reason) {
          this.$message.warning('申请原因不可为空')
          return
        }

        apply(data).then(() => {
          this.$message.success('操作成功')
          this.$router.push('/unread')
        })
      }
      if (this.flowStatus == 2) {
        var data = {
          documentFlowId: this.temp.documentFlowId,
          nextHandleUserId: this.temp.reviewId,
          opinion: this.temp.opinion,
          result: this.temp.result
        }
        if (data.result == null) {
          this.$message.warning('处理结果不可为空')
          return
        }
        if (data.result == 1) {
          if (!data.nextHandleUserId) {
            this.$message.warning('审批人不可为空')
            return
          }
        }
        if (!data.opinion) {
          this.$message.warning('处理意见不可为空')
          return
        }
        contentAudit(data).then(() => {
          this.$message.success('操作成功')
          this.$store.commit('message/FLOW_COUNT', this.$store.state.message.flowCount - 1)
          this.$router.push('/unread')
        })
      }
      if (this.flowStatus == 3) {
        var data = {
          documentFlowId: this.temp.documentFlowId,
          nextHandleUserId: this.temp.reviewId,
          opinion: this.temp.opinion,
          result: this.temp.result
        }
        if (data.result == null) {
          this.$message.warning('处理结果不可为空')
          return
        }
        console.log(data, 'data')
        if (data.result == 1) {
          if (!data.nextHandleUserId) {
            this.$message.warning('审批人不可为空')
            return
          }
        }
        if (!data.opinion) {
          this.$message.warning('处理意见不可为空')
          return
        }

        approval(data).then(() => {
          this.$message.success('操作成功')
          this.$store.commit('message/FLOW_COUNT', this.$store.state.message.flowCount - 1)
          this.$router.push('/unread')
        })
      }
      if (this.flowStatus == 4) {
        var data = {
          documentFlowId: this.temp.documentFlowId,
          documentId: this.temp.documentId,
          effectDate: this.temp.effectDate,
          opinion: this.temp.opinion,
          receiveUserGroupIdList:
            this.receiveUserGroupIdList != null
              ? this.receiveUserGroupIdList
              : null,
          receiveUserIdList:
            this.reviewUserId != null ? this.reviewUserId : null
        }
        if (
          data.receiveUserGroupIdList.length == 0 &&
          data.receiveUserIdList.length == 0
        ) {
          this.$message.warning('借阅的目标不可为空')
          return
        }
        if (!data.opinion) {
          this.$message.warning('处理意见不可为空')
          return
        }

        if (!data.effectDate) {
          this.$message.warning('借阅日期不可为空')
          return
        }
        if (data.documentId == 0) {
          this.$message.warning('文件不可为空')
          return
        }
        release(data).then(() => {
          this.$message.success('操作成功')
          this.$router.push('/unread')
        })
      }
    },
    handleStop() {},
    handleClose() {
      this.$router.push({ path: '/unread' })
    },
    async getDocumentParticulars() {
      const particularsdata = await getDocumentParticulars({
        documentId: this.temp.documentId
      })
      this.temp.documentCode = particularsdata.data.documentCode
      this.particularsdocumentName = particularsdata.data.documentName
      this.v2 = particularsdata.data.version
    },
    //
    // 时间线
    async getNodesHandle() {
      const nodeshandledata = await getNodesHandle({
        documentFlowId: this.temp.documentFlowId
      })
      console.log(nodeshandledata, 'nodeshandledata')
      nodeshandledata.data.forEach((item) => {
        console.log(item, 'item')
        for (var key in this.activities) {
          if (item.phase == this.activities[key].phase) {
            Object.assign(this.activities[key], item)
          }
        }
        console.log(this.activities, 'jjj')
      })

      this.$forceUpdate()
    },
    search(val) {
      clearTimeout(this.timeout)
      var pattern = /^([A-Z]{2}-){3}\d{3}$/
      const data = pattern.test(val)
      this.timeout = setTimeout(() => {
        if (!data) {
          this.temp.documentName = ''
          this.v3 = ''
          this.v4 = ''
          this.temp.previousDocumentId = ''
          this.$message.warning('文件编号格式错误')
          return
        }
        getDocumentByCode({ code: val }).then((item) => {
          this.temp.documentName = item.data.documentName
          this.temp.documentId = item.data.documentId
          this.v1 = item.data.version.slice(0, 1)
          this.v2 = item.data.version.slice(1)
          this.$forceUpdate()
        })
      }, 2000 * Math.random())
    },
    dataList(val) {
      this.temp.reviewName = val
      this.temp.reviewId = val[0].userId
      this.$forceUpdate()
    },
    openReview(val, type, title) {
      // 0为角色 1为角色（总经理，总监） 3为架构 4为架构多选 5部门多选
      this.reviewWindow = val
      if (val == 0) {
        if (
          this.temp.documentLevelNum == 1 ||
          this.temp.documentLevelNum == 2
        ) {
          type = 'management-representative'
          title = '管理者代表'
        } else {
          type = 'qa'
          title = 'QA'
        }
        this.SearchPersonnelTypeData = {
          val: val,
          type: type,
          dialogVisible: true,
          title: title
        }
      } else if (val == 1) {
        if (
          this.temp.documentLevelNum == 1 ||
          this.temp.documentLevelNum == 2
        ) {
          type = 'president'
          title = '总经理'
        } else {
          type = 'director'
          title = '总监'
        }
        this.SearchPersonnelTypeData = {
          val: val,
          type: type,
          dialogVisible: true,
          title: title
        }
      } else if (val == 3) {
        this.SearchPersonnelData = {
          dialogVisible: true
        }
      } else if (val == 4) {
        this.SearchUserListData = {
          dialogVisible: true
        }
      } else if (val == 5) {
        this.SelectGroupListData = {
          dialogVisible: true
        }
      }
    },
    SearchUserList(data) {
      const newData = []
      const idList = []
      data.map((item, index) => {
        idList.push(item.id)
        newData.push({
          id: item.id,
          userName: item.label
        })
      })
      this.reviewUserId = idList
      this.temp.reviewName = newData
      console.log(idList, 'idList')
      this.$forceUpdate()
    },
    UserGroupListData(data) {
      this.receiveUserGroupList = data
      data.map((item) => {
        this.receiveUserGroupIdList.push(item.id)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.inputbox {
  display: flex;
  .input-el {
    text-align: center;
    margin-right: 10px;
  }
}
.input {
  width: 50px;
  text-align: center;
}
.tag {
  margin-right: 10px;
}
.label {
  width: 39%;
}
.buttonleft {
  margin-left: 85%;
}
.inner-container {
  display: -webkit-flex;
  display: flex;
  flex-direction: row;
}

.left-container {
  width: calc(100% - 300px);
}

.right-container {
  width: 300px;

  .el-timeline {
    .el-timeline-item {
      height: 56px;
      line-height: 56px;

      p {
        height: 16px;
        line-height: 16px;
        font-size: 13px;
      }
    }
  }
}
</style>
